#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <string>
#include <unordered_map>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <iostream>
#include <unistd.h>
#include <string>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <functional>
using namespace std;
class Sock
{
public:
    static const int gBacklog = 20;

    static int Socket()
    {
        // 1.创建套接字
        int listenSock = socket(AF_INET, SOCK_STREAM, 0);
        if (listenSock < 0)
        {
            cerr << "socket error" << endl;
            exit(1);
        }
        int opt = 1;
        setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        return listenSock;
    }
    static void Bind(int listenSock, uint16_t port)
    {
        // 2. bind
        // 2.1 填充信息到结构体
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        // 2.2 bind,本地sock写入内核sock
        if (bind(listenSock, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            cerr << "bind error" << endl;
            exit(2);
        }
    }

    static void Listen(int listenSock)
    {
        // 3.监听
        if (listen(listenSock, gBacklog) < 0)
        {
            cerr << "listen error" << endl;
            exit(2);
        }
    }

    static int Accept(int listenSock, uint16_t *peerPort, string *ip) // 后两个是输出型参数
    {
        //  4.连接
        struct sockaddr_in peer;
        socklen_t len = sizeof peer;
        int serviceSock = accept(listenSock, (struct sockaddr *)&peer, &len);
        if (serviceSock < 0)
        {
            cerr << "accept error" << endl;
            return -1;
        }
        // 4.1获取客户端基本信息
        if (peerPort)
            *peerPort = ntohs(peer.sin_port);
        if (ip)
            *ip = inet_ntoa(peer.sin_addr);
        return serviceSock;
    }
};

